package com.edu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.eduservice.entity.EduSubject;
import com.edu.eduservice.entity.excel.SubjectData;
import com.edu.eduservice.service.EduSubjectService;
import com.edu.eduservicebase.exception.GuliException;


public class SubjectExcelListener extends AnalysisEventListener <SubjectData>{

    //因为excel监听器不能交给spring容器j进行管理,需要自己new,不能注入其他对象
    //不能实现数据库操作

    //需要手动注入
    public EduSubjectService eduSubjectService;
    public SubjectExcelListener( ) {
    }
    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }



    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
            if (subjectData ==null){
                throw new GuliException(20001,"文件数据为空!");
            }
            //判断一级分类是否重复
        EduSubject eduoneSubject = this.existOneSubject(subjectData.getOneSubjectName(), eduSubjectService);
            if (eduoneSubject==null){

                EduSubject edusub = new EduSubject();
                edusub.setParentId("0");
                edusub.setTitle(subjectData.getOneSubjectName());
                eduSubjectService.save(edusub);
            }

            //判断二级分类是否重复

        String id=eduoneSubject.getId();

        EduSubject edutwoSubject = this.existTwoSubject(subjectData.getTwoSubjectName(), eduSubjectService,id);
        if (edutwoSubject==null){
            EduSubject edusub = new EduSubject();
            edusub.setParentId(id);
            edusub.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(edusub);
        }

    }

    //判断一级分类
    private EduSubject existOneSubject(String name,EduSubjectService eduSubjectService){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");

        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }
    //判断二级分类
    private EduSubject existTwoSubject(String name,EduSubjectService eduSubjectService,String id){
        QueryWrapper<EduSubject> wrapper =new QueryWrapper();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",id);

        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
